<template>
  <div class="app-container">
    <!-- 查询条件（静态展示） -->
    <el-form :inline="true" label-width="68px">
      <el-form-item label="机柜编号">
          <el-input
              v-model="queryParams.cabinetNo"
              placeholder="机柜编号"
              clearable
          />
      </el-form-item>
      <el-form-item label="名称">
          <el-input
              v-model="queryParams.name"
              placeholder="请输入名称"
              clearable
          />
      </el-form-item>
      <el-form-item label="分类">
          <el-select
              v-model="queryParams.cabinetTypeId"
              placeholder="请选择分类"
              clearable
          >
            <el-option v-for="item in typeQuery" :label="item.name" :value="item.id" >{{item.name}}</el-option>
          </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
            v-hasPermi="['device:cabinet:query']"
            :disabled="sineIe"
            type="primary"
            icon="Search"
            @click="cabinetMachineManagement"
            >搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮（仅展示，不可操作） -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="cabinetAdd">新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button type="success" >修改</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Plus" @click="handleDelete()">删除</el-button>
      </el-col>
    </el-row>

    <!-- 表格数据展示 -->
    <el-table :data="mockTableData" @selection-change="handleselectionchange" v-loading="loading">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="机柜编号" prop="cabinetNo" width="120"/>
      <el-table-column label="名称" prop="name" width="120"/>
      <el-table-column label="分类" prop="cabinetTypeName" width="120"/>
      <el-table-column label="总插槽数" prop="totalSlots" width="100"/>
      <el-table-column label="空闲插槽数" prop="freeSlots" width="100"/>
      <el-table-column label="可用数量" prop="availableNum" width="100"/>
      <el-table-column label="描述" prop="description" />
      <el-table-column label="状态" prop="status" width="80">
        <template #default="scope">
          {{ scope.row.status == '0' ? '未投放' : scope.row.status == '1' ? '使用中' : '故障' }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" />
      <el-table-column label="操作" align="center" width="220">
        <template #default="scope">
          <el-button link type="primary" @click="detailsPopUpWindow(scope.row)" >详情</el-button>
          <el-button link type="primary" v-if="scope.row.status === '0'" @click="cabinetUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" v-if="scope.row.status === '0'" @click="handleDeleteD(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条组件 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        v-model:current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 30, 50]"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
    />

    <!-- 添加/编辑对话框（隐藏） -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body @close="cancel">
      <el-form ref="cabinetRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="编号" prop="cabinetNo">
          <el-input v-model="form.cabinetNo" placeholder="请输入柜机编号" disabled/>
        </el-form-item>
        <el-form-item label="分类" prop="cabinetTypeId">
          <el-select
              v-model="form.cabinetTypeId"
              class="m-2"
              placeholder="分类"
          >
            <el-option
                v-for="item in typeQuery"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addUpdate">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情对话框（隐藏） -->
    <el-dialog title="柜机详细信息" width="50%" v-model="detailsOrNot">
      <el-descriptions title="柜机信息">
        <el-descriptions-item label="机柜编号">{{particulars.cabinetNo}}</el-descriptions-item>
        <el-descriptions-item label="机柜名称">{{particulars.name}}</el-descriptions-item>
        <el-descriptions-item label="总插槽数量">{{particulars.totalSlots}}</el-descriptions-item>
        <el-descriptions-item label="空闲插槽量">{{particulars.freeSlots}}</el-descriptions-item>
        <el-descriptions-item label="已使用插槽">{{particulars.usedSlots}}</el-descriptions-item>
        <el-descriptions-item label="可用数量">{{particulars.availableNum}}</el-descriptions-item>
        <el-descriptions-item label="描述">{{particulars.description}}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{particulars.createTime}}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions title="柜机插槽信息"></el-descriptions>
      <el-table :data="mockSlotData">
        <el-table-column label="插槽编号" prop="slotNo" width="120"/>
        <el-table-column label="使用状态" prop="status" width="100">
          <template #default="scope">
            {{ scope.row.status == '1' ? '占用' : '空闲' }}
          </template>
        </el-table-column>
        <el-table-column label="充电宝标号" prop="powerBankNo" width="130"/>
        <el-table-column label="充电宝电量(%)" prop="electricity" width="130"/>
        <el-table-column label="创建时间" prop="createTime" align="center">
          <template #default="scope">
            <span>{{scope.row.createTime}}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup name="StaticCabinet">
import { getList,allCheck,getCabinet,addCabinet,updateCabinet,getCode,delCabinet,deletedms } from '../../../api/device/cabinet.js'

const sineIe = ref(false)
const total = ref(0)
const mockTableData = ref([])
const typeQuery = ref([])
const detailsOrNot = ref(false)
const particulars = ref({})
const mockSlotData = ref([])
const open = ref(false)
const ids = ref([])
const form = ref({
  cabinetNo: '',
  name: '',
  cabinetTypeId: '',
  description: ''
})
const title = ref('')

const searchParams = reactive({
  queryParams:{
    id: '',
    cabinetNo: '',
    name: '',
    cabinetTypeId: '',
    pageNum: 1,
    pageSize: 10
},
  rules: {
    cabinetTypeId: [
      { required: true, message: "分类必须选择", trigger: "blur" }
    ],
    name: [
      { required: true, message: "名称不能为空", trigger: "blur" }
    ],
    cabinetNo: [
      { required: true, message: "柜机编号不能为空", trigger: "blur" }
    ],
  }

})

const {queryParams,rules} = toRefs(searchParams)

async function handleDeleteD(id){
  let _ids = id;
  await proxy.$modal.confirm('是否确认删除充电宝柜机编号为"' + _ids + '"的数据项？')

  await deletedms(_ids);

  await cabinetMachineManagement();

  await proxy.$modal.msgSuccess("删除成功");
}

/**
 * 取消
 */
function cancel() {
  open.value = false
  localStorage.removeItem("layout-setting")
}
/**
 * 柜机新增
 */
function cabinetAdd() {

  form.value = {}

  const item = localStorage.getItem('layout-setting');

  if (item != null && item.trim() !== '') {
    form.value.cabinetNo = item;
  } else {
    getCode().then((res) => {

      if (res.code === 200) {  // 先检查响应状态
        const newCode = res.msg;  // 获取返回的编号

        localStorage.setItem('layout-setting', newCode);
        form.value.cabinetNo = newCode;
        console.log("新增编号：", newCode);
      } else {
        console.error("获取编号失败：", res);
      }
    }).catch(error => {
      console.error("请求异常：", error);
    });
  }
  title.value = 'add';
  open.value = true;
}

import { getCurrentInstance } from 'vue'

// 在 setup 中获取 proxy
const { proxy } = getCurrentInstance()

// 修改后的 addUpdate 方法
function addUpdate() {
  proxy.$refs["cabinetRef"].validate(valid => {
    if (valid) {
      const operation = title.value === 'add' ? addCabinet : updateCabinet

      operation(form.value).then(res => {
        if (res.code === 200) {
          proxy.$modal.msgSuccess(`${title.value === 'add' ? '新增' : '修改'}成功`)
          cabinetMachineManagement()
          open.value = false
          localStorage.removeItem("layout-setting")
        } else {
          proxy.$modal.msgError(res.msg || "操作失败")
        }
      }).catch(error => {
        proxy.$modal.msgError("请求失败: " + (error.message || "未知错误"))
        console.error("操作失败:", error)
      })
    }
  })
}
/**
 * 删除按钮操作
 * */
function handleDelete() {
  let _ids = ids.value;


  console.log("删除的数据：", _ids);

  proxy.$modal.confirm(`是否确认删除编号为 ${_ids.join(',')} 的数据？`)
      .then(() => {
        return delCabinet(_ids);
      })
      .then(() => {
        cabinetMachineManagement();
        proxy.$modal.msgSuccess("删除成功");
      })
      .catch(console.error);
}
/**
 * 柜机修改
 */
function cabinetUpdate(row){
  open.value = true
  form.value = JSON.parse(JSON.stringify(row));
  console.log("修改的数据：",form.value)
  title.value = 'update'
  cabinetTypeList()
}

/**
 * 详情弹窗
 */
function detailsPopUpWindow(row){
  detailsOrNot.value = true
  particulars.value = row
  getCabinet(row.id).then((res) => {
    mockSlotData.value = res.data
    console.log("充电宝详情：",mockSlotData.value)
  })
}

/**
 * 查询柜机管理列表
 */
const cabinetMachineManagement = async () => {
  try {
    const res = await getList(queryParams.value)

    mockTableData.value = res.data.list
    total.value = res.data?.total || res.total || 0
    console.log('柜机列表数据:', mockTableData.value)

  } catch (e) {
    console.error('获取柜机列表失败:', e)
    mockTableData.value = []
  }
}
/**
 * 查询柜机类型列表
 * @param val
 */
const cabinetTypeList = async () =>{
  try {
    allCheck().then(res => {
      typeQuery.value = res.data
      console.log("柜机类型查询：",res.data)
    })
  }catch (e){

  }
}
/**
 * 重置
 * @param val
 */
function resetQuery(){
  queryParams.value = {
    cabinetNo: '',
    name: '',
    cabinetTypeId: '',
    pageNum: 1,
    pageSize: 10
  }
}

/**
 * 每页条数变化处理
  */
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val;
  cabinetMachineManagement(); // 调用获取数据的方法
};

/**
 * 当前页码变化处理
  */
const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val;
  cabinetMachineManagement(); // 调用获取数据的方法
};

/**
 * 多选框选中数据
 */
function handleselectionchange(selection){
  ids.value = selection.map(item => item.id)
  console.log("多选框选中数据：",ids.value)
}

onMounted(() => {
  cabinetTypeList()
  cabinetMachineManagement()
})
</script>

<style scoped>
.static-value {
  display: inline-block;
  min-width: 120px;
  color: #666;
}
</style>